//
//  ViewController.swift
//  iCloudDocumentsDemo
//
//  Created by zxy on 2021/6/21.
//

import UIKit

class ViewController: UIViewController, UIDocumentPickerDelegate {
    
    var filePath = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orange
        
        let btn = UIButton(frame: CGRect(x: 100, y: 200, width: 80, height: 40))
        btn.setTitle("Open iCloud", for: .normal)
        btn.sizeToFit()
        btn.backgroundColor = UIColor.purple
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(jumpToICloud), for: .touchUpInside)
        
        let btn2 = UIButton(frame: CGRect(x: 250, y: 200, width: 80, height: 40))
        btn2.setTitle("Get File", for: .normal)
        btn2.sizeToFit()
        btn2.backgroundColor = UIColor.green
        view.addSubview(btn2)
        btn2.addTarget(self, action: #selector(getFile), for: .touchUpInside)
    }
    
    @objc func jumpToICloud() {
        //打开iCloud文件界面
        let menuVc = UIDocumentPickerViewController(documentTypes: ["public.data",
                                                                    "public.item",], in: .import)
        menuVc.modalPresentationStyle = .fullScreen
        menuVc.delegate = self
        present(menuVc, animated: true, completion: nil)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print(urls)
        if let url = urls.first {
            filePath = url.absoluteString
            let error = NSErrorPointer(nil)
            let fileCoor = NSFileCoordinator()
            fileCoor.coordinate(readingItemAt: url, options: [], error: error) { fileUrl in
                //print(fileUrl)
                let fileName = fileUrl.lastPathComponent
                //print(fileName)
                do {
                    let data = try Data(contentsOf: fileUrl, options: .mappedRead)
                    let arr = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
                    let documentPath = arr.last
                    print(documentPath)
                    let localFileName = documentPath?.appending("/").appending(fileName) ?? ""
                    let desPath = URL(fileURLWithPath: localFileName)
                    try data.write(to: desPath, options: .atomic)
                    print(data.count)
                    filePath = localFileName
                } catch let error as Error? {
                    print(error?.localizedDescription)
                }
            }
        }
    }

    //open模式
//    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
//        print(urls)
//        if let url = urls.first {
//            filePath = url.absoluteString
//            let fileAuth = url.startAccessingSecurityScopedResource()
//            let error = NSErrorPointer(nil)
//            if fileAuth {
//                let fileCoor = NSFileCoordinator()
//                fileCoor.coordinate(readingItemAt: url, options: [], error: error) { fileUrl in
//                    print(fileUrl)
//                    let fileName = fileUrl.lastPathComponent
//                    print(fileName)
//                    do {
//                        let data = try Data(contentsOf: fileUrl, options: .mappedRead)
//                        print(data.count)
//                    } catch let error as Error? {
//                        print(error?.localizedDescription)
//                    }
//                }
//            }
//        }
//    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("documentPickerWasCancelled")
    }
    
    @objc func getFile() {
        let url = URL(fileURLWithPath: filePath)
        // 带throws的方法需要抛异常
        do {
            /*
             * try 和 try! 的区别
             * try 发生异常会跳到catch代码中
             * try! 发生异常程序会直接crash
             */
            let data = try Data(contentsOf: url)
            //let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            print(data.count)
            
        } catch let error as Error? {
            print(error?.localizedDescription)
        }
    }
}

